<template>
  <div class="app-container">
    <div class="custom_card">
      <!-- 添加或修改角色配置对话框 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="form.roleName" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="6" :offset="1">
            <el-form-item prop="roleKey">
              <span slot="label">
                <el-tooltip
                  content="控制器中定义的权限字符，如：//@PreAuthorize(`@ss.hasRole('admin')`)"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                权限字符
              </span>
              <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
            </el-form-item>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="角色顺序" prop="roleSort">
              <el-input-number
                v-model="form.roleSort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="菜单权限">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="form.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')"
            >父子联动</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="首页模块">
          <el-checkbox-group v-model="financialManagementList">
            <template v-for="item in dict.type.financial_management">
              <el-checkbox
                :label="String(item.value)"
                :key="String(item.value)"
              >{{ item.label }}</el-checkbox
              >
            </template>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="常用工具" v-if="financialManagementList.includes('3')">
          <el-checkbox-group v-model="commonToolsList">
            <template v-for="item in dict.type.common_tools">
              <el-checkbox
                :label="String(item.value)"
                :key="String(item.value)"
                >{{ item.label }}</el-checkbox
              >
            </template>
          </el-checkbox-group>
        </el-form-item>

<!--        <el-form-item label="运营报表">-->
<!--          <el-checkbox-group v-model="operatingReportsList">-->
<!--            <template v-for="item in dict.type.operating_reports">-->
<!--              <el-checkbox-->
<!--                :label="String(item.value)"-->
<!--                :key="String(item.value)"-->
<!--                >{{ item.label }}</el-checkbox-->
<!--              >-->
<!--            </template>-->
<!--          </el-checkbox-group>-->
<!--        </el-form-item>-->
        <el-form-item label="底部导航">
          <el-checkbox-group v-model="navigationList">
            <template v-for="item in dict.type.navigation">
              <el-checkbox
                :label="String(item.value)"
                :key="String(item.value)"
                >{{ item.label }}</el-checkbox
              >
            </template>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { addRole, updateRole, getRole } from '@/api/system/role'
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from '@/api/system/menu'

export default {
  name: 'Role',
  dicts: [
    'sys_normal_disable',
    'common_tools',
    'financial_management',
    'operating_reports',
    'navigation',
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: '',
      menuExpand: false,
      menuNodeAll: false,
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      financialManagementList: [],
      commonToolsList: [],
      operatingReportsList: [],
      navigationList: [],
      // 表单参数
      form: {
        roleSort: 0,
        status: '0',
        menuCheckStrictly: true,
      },
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
        ],
        roleSort: [
          { required: true, message: '角色顺序不能为空', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    const roleId = this.$route.params && this.$route.params.roleId
    this.financialManagementList = []
    this.commonToolsList = []
    this.operatingReportsList = []
    this.navigationList = []
    if (roleId) {
      const roleMenu = this.getRoleMenuTreeselect(roleId)
      getRole(roleId).then((response) => {
        this.form = response.data

        this.commonToolsList =
          this.form.commonTools != null && this.form.commonTools != ''
            ? this.form.commonTools.split(',')
            : []
        console.log(this.commonToolsList)
        this.financialManagementList =
          this.form.financialManagement != null &&
          this.form.financialManagement != ''
            ? this.form.financialManagement.split(',')
            : []
        this.operatingReportsList =
          this.form.operatingReports != null && this.form.operatingReports != ''
            ? this.form.operatingReports.split(',')
            : []
        this.navigationList =
          this.form.navigation != null && this.form.navigation != ''
            ? this.form.navigation.split(',')
            : []
        this.$nextTick(() => {
          roleMenu.then((res) => {
            let checkedKeys = res.checkedKeys
            checkedKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false)
              })
            })
          })
        })
        this.title = '修改角色'
      })
    } else {
      this.getMenuTreeselect()
    }
  },
  methods: {
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data
      })
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then((response) => {
        this.menuOptions = response.menus
        return response
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 取消按钮
    cancel() {
      this.goBack()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      ;(this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: '0',
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
        })
      this.resetForm('form')
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false
      }
    },
    goBack() {
      this.reset()
      this.$store.commit('app/SET_MMVREF')
      this.$router.go(-1) // 返回
      //关闭子页面
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex(
          (item) => item.path === this.$route.path
        ),
        1
      )
      this.$router.push(
        this.$store.state.tagsView.visitedViews[
          this.$store.state.tagsView.visitedViews.length - 1
        ].path
      )
      this.$destroy()
    },
    /** 提交按钮 */
    submitForm: function () {
      this.form.commonTools =
        this.commonToolsList.length > 0 ? String(this.commonToolsList) : null
      this.form.financialManagement =
        this.financialManagementList.length > 0
          ? String(this.financialManagementList)
          : null
      this.form.operatingReports =
        this.operatingReportsList.length > 0
          ? String(this.operatingReportsList)
          : null
      this.form.navigation =
        this.navigationList.length > 0 ? String(this.navigationList) : null
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            updateRole(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.goBack()
            })
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            addRole(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.goBack()
            })
          }
        }
      })
    },
  },
}
</script>
